<?php
namespace App\Service\Chat;

use App\Constants\Chat\RedisKey;
use App\Foundation\Traits\Singleton;
use App\Model\Auth\User;
use App\Model\Chat\ChatGroup;
use App\Model\Chat\GroupChatHistory;
use App\Model\Chat\GroupMember;
use App\Model\Chat\GroupRelation;
use App\Pool\Redis;
use App\Service\BaseService;

/**
 * 组消息服务类
 * Class GroupService
 * @package App\Service\Chat
 * @Author YiYuan-Lin
 * @Date: 2021/5/8
 */
class GroupService extends BaseService
{
    use Singleton;

    /**
     * 获取群成员列表
     * @param $chat_id
     * @return array|mixed|string
     */
    public static function getGroupMembers($chat_id): array
    {
        $key = RedisKey::CHAT_GROUP_MEMBER_KEY . ':' . $chat_id;
        $redis = Redis::getInstance();
        $cache = $redis->get($key);
        if ($cache) {
            return $cache;
        }
        $data = GroupMember::query()->select('*')->where([
                'list_id' => $chat_id]
        )->get()->toArray();
        $data = array_column($data, null, 'user_id');
        $redis->set($key, $data);
        return $data;
    }

    /**
     * 删除群成员缓存
     * @param $chat_id
     * @return bool
     */
    public static function clearGroupMemberCache($chat_id): bool
    {
        $key = RedisKey::CHAT_GROUP_MEMBER_KEY . ':' . $chat_id;
        $redis = Redis::getInstance();
        return $redis->del($key);
    }

    /**
     * 清除群缓存
     */
    public static function clearGroupCache($chat_id): bool
    {
        $redis = Redis::getInstance();
        $key = RedisKey::CHAT_GROUP_KEY . ':' . $chat_id;
        return $redis->del($key);
    }

    /**
     * 获取群详情
     */
    public static function getGroupInfo($chat_id)
    {
        $redis = Redis::getInstance();
        $key = RedisKey::CHAT_GROUP_KEY . ':' . $chat_id;
        $cache = $redis->get($key);
        if ($cache) {
            return $cache;
        }
        $cache = ChatGroup::query()->select('*')->where([
            'chat_id' => $chat_id
        ])->first()->toArray();
        $redis->set($key, $cache);
        return $cache;
    }



}
